<html>

<head>
    <title>聊天室</title>
    <!-- 自适配手机端尺寸 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />
    <style>
        .line {
            display: flex;
            justify-content: center;
            margin: 1rem;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .line-top {
            display: flex;
            justify-content: space-between;
            margin: 1rem;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .line-title {
            width: 200px;
            overflow: hidden;
        }

        .line-content {
            width: 200px;
            overflow: hidden;
        }

        .msg {
            display: flex;
            justify-content: flex-start;
            margin: 0.5rem;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .content {
            display: flex;
            flex-direction: column;
            width: 400px;
            border: solid 1px;
            padding: 1rem;
            overflow-x: scroll;
            max-height: 500px;
            overflow-y: auto;
            min-height: 100px;
        }

        .name {
            width: 35px;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .time {
            color: gray;
        }

        .info {
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: lightgray;
            padding: 1rem;
            border-radius: 1rem;
            opacity: 0.9;
        }
    </style>
</head>

<body>
    <div class="line">
        <div class="content">
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好111111111111111111122222222222222222</div>-->
            <!--            </div>-->
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好</div>-->
            <!--            </div>-->
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好</div>-->
            <!--            </div>-->
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好</div>-->
            <!--            </div>-->
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好</div>-->
            <!--            </div>-->
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好</div>-->
            <!--            </div>-->
            <!--            <div class="msg">-->
            <!--                <div class="time">上午3:01:16</div>-->
            <!--                <div class="name">aaa</div>-->
            <!--                <div>:</div>-->
            <!--                <div>你好</div>-->
            <!--            </div>-->
        </div>
        <div>
            <div class="line">
                <div>用户名称</div>
                <input name="username" placeholder="请输入用户名" value="游客" />
            </div>
            <div class="line">
                <div>消息内容</div>
                <input name="message" placeholder="请输入内容" value="" />
            </div>
            <div class="line">
                <button>发送</button>
                <button>清屏</button>
            </div>
            <div class="line-top">
                <div class="line-title">消息排行</div>
                <div id="msgHis">
                    <!-- <div>user1</div>
                <div>user1</div>
                <div>user1</div> -->
                </div>
            </div>
            <div class="line-top">
                <div class="line-title">在线列表</div>
                <div id="online">
                    <!-- <div>user1</div>
                <div>user1</div>
                <div>user1</div> -->
                </div>
            </div>
        </div>
    </div>

    <!-- <div class="info">
    提示消息
</div> -->
    <script type="module">

        let elContent = document.getElementsByClassName('content').item(0)
        let elUsername = document.getElementsByName('username').item(0)
        let elMessage = document.getElementsByName('message').item(0)
        //let msgHisMessage = document.getElementsByName('message').item(0)
        let btnSend = document.getElementsByTagName('button').item(0)
        let btnClear = document.getElementsByTagName('button').item(1)

        let elMsgHis = document.getElementById('msgHis')
        let elOnline = document.getElementById('online')

        let queryGet = async (url) => await (await fetch(url)).json()
        setInterval(async () => {
            let res = await queryGet('http://localhost:9090/chatApi/getTopUserMessage')
            if (res.code == 0) {
                let dataArr = res.data
                Array.from(elMsgHis.children).forEach(e => e.remove())
                dataArr.forEach(e => {
                    let { name, score, id } = e
                    let msg = `${name} ${score}`
                    let el = document.createElement('div')
                    el.innerHTML = msg;
                    elMsgHis.appendChild(el)
                })

            }
        }, 5000);
        setInterval(async () => {
            let res = await queryGet('http://localhost:9090/chatApi/getOnlineUsers')
            if (res.code == 0) {
                let dataArr = res.data
                Array.from(elOnline.children).forEach(e => e.remove())
                dataArr.forEach(e => {
                    let sp = e.split('::')
                    let userId = sp[0]
                    let name = sp[1]
                    let msg = `${name}`
                    let el = document.createElement('div')
                    el.innerHTML = msg;
                    elOnline.appendChild(el)
                })

            }
        }, 5000);


        let queryObj = decodeURIComponent(location.search).split('?').pop().split('&').reduce((res, ele, ind) => {
            let sp = ele.split('=')
            res[sp[0]] = sp[1]
            return res
        }, {})
        if (!queryObj.userId) {
            alert('用户id未填写')
            location.href = '/'
            throw new Error('用户id未填写')
        }
        let serverUrl = 'http://localhost:9090'
        let wsUrl = 'ws://localhost:9090/chat/' + queryObj.userId
        let ws
        let wsErr = false
        function doConnect() {
            ws = new WebSocket(wsUrl)
            ws.onclose = () => {
                if (!wsErr) {
                    showMsg({ username: '系统', message: '聊天室已断开' })
                    wsErr = true
                }
                setTimeout(doConnect, 2000)
            }
            ws.onopen = async () => {
                wsErr = false
                showMsg({ username: '系统', message: '聊天室已连接' })

                let detailUrl = `http://localhost:9090/user/detail?userId=${queryObj.userId}`
                let res = await queryGet(detailUrl)
                if (res.code == 0) {
                    elUsername.value = res.data.name
                }
            }
            ws.onmessage = (event) => {
                let data = event.data
                try {
                    let msg = JSON.parse(data)
                    showMsg(msg)
                } catch (err) {
                    showMsg({ username: '系统', message: String(data) })
                }
            }
        }
        doConnect()

        function getMsg() {
            let username = elUsername.value
            let message = elMessage.value
            return { username, message }
        }
        function showMsg(msg = { username: '', time: '', message: '' }) {
            let { username = '', time = Date.now(), message = '' } = msg
            let timeStr
            if (typeof (time) == 'number') {
                timeStr = new Date(time).toLocaleTimeString()
            } else {
                timeStr = new Date(String(time).substring(0, 19)).toLocaleTimeString()
            }
            let msgLine = document.createElement('div')
            msgLine.className = 'msg'
            msgLine.innerHTML = `<div class="name">${username}</div>
            <div class="time">${timeStr}</div>
            <div>${message}</div>`
            elContent.insertBefore(msgLine, elContent.firstElementChild)
        }
        function info(msg = '') {
            let elInfo = document.createElement('div')
            elInfo.className = 'info'
            elInfo.innerHTML = `${msg}`
            document.body.appendChild(elInfo)
            setTimeout(() => elInfo.remove(), 2000)
        }
        function sendMsg() {
            let { username, message } = getMsg()
            if (!username) {
                info('用户名称未填写')
                return
            }
            if (!message) {
                info('消息内容未填写')
                return
            }
            localStorage['username'] = username
            elMessage.value = ''
            ws.send(JSON.stringify({ username, message }))
        }
        function clear() {
            elContent.innerHTML = ''
        }
        async function load() {
            let res = await fetch(serverUrl + "/history/listChatHistory?page=1&pageSize=1000")
            let json = await res.json()
            window.json = json
            console.log('json', json)
            if (json.data.records != null) {
                // for (let i = 0; i < json.data.records.length; i++) {
                //     let his = json.data.records[i]
                //     showMsg(his)
                // }
                // @since 2025-3-20 15:24:38 修复历史消息内容顺序不是最新的在前面的问题
                json.data.records.reverse().forEach(his => showMsg(his))
            }
        }
        document.body.onload = async () => {
            btnSend.onclick = sendMsg
            btnClear.onclick = clear
            elUsername.value = localStorage['username'] || elUsername.value
            clear()
            load()
        }




    </script>

</body>

</html>